home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2284 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.8 KB  |  69 lines

  1. Path: locutus.rchland.ibm.com!usenet
  2. From: pstaite@vnet.ibm.com
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: How do I prevent deleting of an object that is still being used?
  5. Date: 16 Jan 1996 16:07:51 GMT
  6. Organization: IBM OS/2 Device Driver Development  Rochester, MN
  7. Message-ID: <4dgign$11vi@locutus.rchland.ibm.com>
  8. References: <4dg9in$s5h@utopia.hacktic.nl>
  9. Reply-To: pstaite@vnet.ibm.com
  10. NNTP-Posting-Host: warpone.rchland.ibm.com
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4dg9in$s5h@utopia.hacktic.nl>, Mike Tavares <MIKET@cdynamics.com> writes:
  14. >
  15. >I have some classes:
  16.  
  17. This problem cries out for reference counting ... :-)  See additions to 
  18. your classes below:
  19.  
  20. >class menuItem
  21. >    {
  22. >    ...
  23.  
  24.   public:
  25.     menuItem() : refs( 1 ) {}
  26.     void dropref() { if( ! --refs ) delete this; }
  27.     void addref() { ++refs; }
  28.   private:
  29.     int refs;
  30. >    }
  31.  
  32. Note, copy construction should set the ref count to 1 on the new 
  33. menuItem, but leave the source object's ref count alone.  Assignment
  34. should leave the ref counts of both objects alone.
  35.  
  36. >
  37. >
  38. >
  39. >class   menu
  40. >    {
  41. >
  42. >    list<menuItem>  theItems    // the items that are on this menu.
  43.  
  44. Looks like the menu is owning it's own copy (by value) of the items. 
  45. Maybe you meant:
  46.  
  47.     list<menuItem*> theItems;
  48.  
  49.  
  50.  
  51.      Register( menuItem  &anItem ) {
  52.         anItem.addref();
  53.         theItems.add( &anItem ); }
  54.  
  55.     ~menu() {
  56.         // for each menuItem in theItems
  57.         theItems.remove( next_item )->dropref();
  58. }
  59.  
  60. One caution:  make sure the list doesn't try to do anything with the
  61. menuItems once you've called dropref() on them.  After that call, 
  62. they may be gone.  You might want to extract/remove the element 
  63. (ptr/ref) from the list then call dropref() on it.
  64.  
  65.  
  66. Phil Staite, team OS/2
  67. internet: pstaite@vnet.ibm.com  internal: pstaite@rchland
  68.  
  69.